package com.hxy.manager.activity.today;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;


import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.hxy.manager.R;
import com.hxy.manager.entity.TodayPriceEntity;

/**
 * Created by 傲寒宏志 on 2018/1/13.
 */

public class TodayAddActivity extends Activity {
    ImageView imageView;
    EditText editText7;
    EditText editText8;
    EditText editText9;
    TodayPriceEntity tp;
    Uri uri;
    private static String picFileFullName="";
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private static final int PICK_IMAGE_ACTIVITY_REQUEST_CODE = 200;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.today_add);
        setTitle("添加商品");

        getActionBar().setDisplayHomeAsUpEnabled(true);//向上返回
        Calendar now = Calendar.getInstance();


        editText9=(EditText)findViewById(R.id.editText9);
        editText9.setText(now.get(Calendar.YEAR)+"年"+(now.get(Calendar.MONTH) + 1) +"月"+now.get(Calendar.DAY_OF_MONTH)+"日");

        tp=new TodayPriceEntity();
        imageView=(ImageView)findViewById(R.id.imageView7);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //获取两个权限，一个是相机权限，一个是读写外部存储器权限
                if (ContextCompat.checkSelfPermission(TodayAddActivity.this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(TodayAddActivity.this,new String[]{Manifest.permission.CAMERA},1); }
                else if(ContextCompat.checkSelfPermission(TodayAddActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(TodayAddActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                }
                else
                takePicture();
            }
        });
        imageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {

                Intent intent = new Intent(Intent.ACTION_VIEW);
//Uri mUri = Uri.parse("file://" + picFile.getPath());Android3.0以后最好不要通过该方法，存在一些小Bug
             //   intent.setDataAndType(Uri.fromFile(picFile), "image/*");
                intent.setDataAndType(uri, "image/*");
                startActivity(intent);

                return false;
            }
        });


        Button save = (Button)findViewById(R.id.save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editText7=(EditText)findViewById(R.id.editText7);
                editText8=(EditText)findViewById(R.id.editText8);
                editText9=(EditText)findViewById(R.id.editText9);
                if(editText7.getText().toString().equals("")){
                    toast("名字不能为空！");
                }
                else if(editText8.getText().toString().equals("")){
                    toast("价格不能为空！");
                }
                    /*
                else if(editText9.getText().toString().equals("")){
                    toast("日期不可为空！");

                    SQLiteDatabase db1 = openOrCreateDatabase("My_DB.db",MODE_PRIVATE,null);
                    db1.execSQL("create table if not exists TodayPrice(id integer primary key autoincrement, name text,price text,date text,photo text,time text)");
                    //取当前年月日时分秒最为编码
                    Date d = new Date();
                    //格式化为一串数字
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                    String dateNowStr = sdf.format(d);

                    db1.execSQL("insert into TodayPrice(name,price,date,photo,time)values('"+tp.getName()+"','"+tp.getPrice()+"','"+tp.getDate()+"','"+tp.getPhoto()+"','"+dateNowStr+"')");

                }*/
                else {
                    tp.setPhoto(picFileFullName);
                    tp.setName(editText7.getText().toString());
                    tp.setPrice(editText8.getText().toString());
                    tp.setDate(editText9.getText().toString());
                    SQLiteDatabase db = openOrCreateDatabase("My_DB.db",MODE_PRIVATE,null);
                    db.execSQL("create table if not exists TodayPrice(id integer primary key autoincrement, name text,price text,date text,photo text,time text)");
                    Log.i("kan","TodayAdd数据库连接成功，Todayprice打开成功!");
                    //取当前年月日时分秒最为编码
                    Date d = new Date();
                    //格式化为一串数字
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                    String dateNowStr = sdf.format(d);
                    Log.i("kan",tp.getName()+"\t"+tp.getPrice()+"\t"+tp.getDate()+"\t"+tp.getPhoto()+"\t"+dateNowStr);
                    db.execSQL("insert into TodayPrice(name,price,date,photo,time)values('"+tp.getName()+"','"+tp.getPrice()+"','"+tp.getDate()+"','"+tp.getPhoto()+"','"+dateNowStr+"')");
                    Log.i("kan","插入TodayPrice成功！");
                    toast("保存成功！");
                    picFileFullName="";
                    editText7.setText("");
                    editText8.setText("");
                 //   editText9.setText("");
                    db.close();
                }

            }
        });





    }

    //打开相机
    public void takePicture(){
        String state = Environment.getExternalStorageState();
        //判断外置存储器是否挂载。
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File outDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            if (!outDir.exists()) {
                outDir.mkdirs();
            }

            //取当前年月日时分秒最为编码
            Date d = new Date();
            //格式化为一串数字
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String dateNowStr = sdf.format(d);

            File outFile =  new File(outDir,"CAI"+dateNowStr + ".jpg");
          //  File outFile =  new File(outDir, System.currentTimeMillis() + ".jpg");
            picFileFullName = outFile.getAbsolutePath();
            //得到图片的uri
            uri=Uri.fromFile(outFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            //跳转到相机滞后于接收返回值（文件地址），再onActivityResult里面处理
            startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        } else{
            //  Log.e(tag, "无法挂在存储器");
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
            //    Log.e(tag, "="+picFileFullName);
               toast("保存路径："+picFileFullName);
                setImageView(picFileFullName);
            } else if (resultCode == RESULT_CANCELED) {

            } else {

             //   Log.e(tag, "");
            }
        } else
            //选择图片的
            if (requestCode == PICK_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                //返回值得到的是文件地址！
                Uri uri = data.getData();
                if(uri != null){
                    String realPath = getRealPathFromURI(uri);
              //      Log.e(tag, ""+realPath);
                    toast("图片路径："+realPath);
                    //设置图片，就可以了
                    setImageView(realPath);
                }else{
               //     Log.e(tag, "");
                }
            }
        }
    }

    private void setImageView(String realPath){

       //这个地方需要文件读写权限呢，没有权限，会一直为null！
        //所以安卓6.0以上需要加入一些代码解决！
        //if (ContextCompat.checkSelfPermission(Today_add.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
        //    ActivityCompat.requestPermissions(Today_add.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1); }
        //else {

        Bitmap bmp = BitmapFactory.decodeFile(realPath);
        int degree = readPictureDegree(realPath);
        if(degree <= 0){
            imageView.setImageBitmap(bmp);
        }else{
         //   Log.e(tag, "rotate:"+degree);
            //
            Matrix matrix=new Matrix();
            //
            matrix.postRotate(degree);
            //
            Bitmap resizedBitmap=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),bmp.getHeight(),matrix,true);
            imageView.setImageBitmap(resizedBitmap);
        }

    }

    public String getRealPathFromURI(Uri contentUri){
        try{
            String[] proj = {MediaStore.Images.Media.DATA};
            // Do not call Cursor.close() on a cursor obtained using this method,
            // because the activity will do that for you at the appropriate time
            Cursor cursor = this.managedQuery(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }catch (Exception e){
            return contentUri.getPath();
        }
    }


    public static int readPictureDegree(String path) {
        int degree  = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    public void toast(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
      //  getMenuInflater().inflate(R.menu.main,menu);
        return super.onCreateOptionsMenu(menu);
    }


    public boolean onOptionsItemSelected(MenuItem item){

        switch(item.getItemId()){
        case android.R.id.home:  //默认添加的
		      finish();  
		      break;  }
        return false;
    }
}
